package com.easylinkin.linkappapi.quality.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.toolkit.CollectionUtils;
import com.easylinkin.linkappapi.common.service.CommonService;
import com.easylinkin.linkappapi.common.utils.excel.ExcelConstant;
import com.easylinkin.linkappapi.common.utils.excel.ExcelTools;
import com.easylinkin.linkappapi.common.utils.io.OutputStreamUtil;
import com.easylinkin.linkappapi.quality.entity.QualityQuestionDealRecord;
import com.easylinkin.linkappapi.quality.entity.QualityQuestionInfo;
import com.easylinkin.linkappapi.quality.entity.vo.QualityQuestionDealRecordVo;
import com.easylinkin.linkappapi.quality.entity.vo.QuestionDealRecordVo;
import com.easylinkin.linkappapi.quality.mapper.QualityQuestionDealRecordMapper;
import com.easylinkin.linkappapi.quality.mapper.QualityQuestionInfoMapper;
import com.easylinkin.linkappapi.quality.service.QualityQuestionDealRecordService;
import com.easylinkin.linkappapi.quality.util.QualityMessageUtils;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import com.easylinkin.linkappapi.security.entity.LinkappUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import site.morn.rest.RestBuilders;
import site.morn.rest.RestMessage;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * QualityQuestionDealRecord表服务实现类
 *
 * @author zhengwen
 * @date 2022/08/16
 */
@Slf4j
@Service("appQualityQuestionDealRecordService")
public class QualityQuestionDealRecordServiceImpl extends ServiceImpl
        <QualityQuestionDealRecordMapper, QualityQuestionDealRecord> implements QualityQuestionDealRecordService {
    @Resource
    private CommonService commonService;
    @Resource
    private LinkappUserContextProducer linkappUserContextProducer;

    @Resource
    private QualityQuestionInfoMapper questionInfoMapper;


    @Override
    public boolean saveOne(QualityQuestionDealRecord appQualityQuestionDealRecord) {
        commonService.setCreateAndModifyInfo(appQualityQuestionDealRecord);
        // appQualityQuestionDealRecord.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
        validParamRequired(appQualityQuestionDealRecord);
        validRepeat(appQualityQuestionDealRecord);
        validParamFormat(appQualityQuestionDealRecord);
        return save(appQualityQuestionDealRecord);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateOne(QualityQuestionDealRecord appQualityQuestionDealRecord) {
        Assert.notNull(appQualityQuestionDealRecord.getId(), "id不能为空");
        commonService.setModifyInfo(appQualityQuestionDealRecord);
        //appQualityQuestionDealRecord.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
        validRepeat(appQualityQuestionDealRecord);
        validParamFormat(appQualityQuestionDealRecord);
        return updateById(appQualityQuestionDealRecord);
    }

    @Override
    public IPage<QualityQuestionDealRecord> selectPage(Page page, QualityQuestionDealRecord appQualityQuestionDealRecord) {
        //appQualityQuestionDealRecord.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
        return baseMapper.selectPage(page, appQualityQuestionDealRecord);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteByIds(List<Long> idList) {
        return removeByIds(idList);
    }

    @Override
    public void export(QualityQuestionDealRecord appQualityQuestionDealRecord, HttpServletRequest request, HttpServletResponse
            response) {

        IPage<QualityQuestionDealRecord> page = selectPage(new Page(0, -1), appQualityQuestionDealRecord);
        List<QualityQuestionDealRecord> records = page.getRecords();
        List
                <QualityQuestionDealRecordVo> appQualityQuestionDealRecordVos = new ArrayList<>();
        for (QualityQuestionDealRecord expert : records) {
            appQualityQuestionDealRecordVos.add(new QualityQuestionDealRecordVo(expert));
        }

        String keyValue = "名称:name,租户id:tenantId";
        String title = "QualityQuestionDealRecord导出数据";
        String fileName = title + ".xls";
        try {
            OutputStream outputStream = OutputStreamUtil
                    .getOutputStream(request, response, fileName);
            ExcelTools.exportExcel(outputStream, keyValue, appQualityQuestionDealRecordVos, ExcelConstant.XLS, title);
            response.flushBuffer();
            outputStream.close();
        } catch (IOException e) {
            log.error("excel导出失败", e);
            throw new RuntimeException("excel导出失败！IOException异常" + e.getMessage());
        } catch (Exception e) {
            log.error("excel导出失败", e);
            throw new RuntimeException("excel导出失败！" + e.getMessage());
        }
    }

    @Override
    public RestMessage addDealInfo(QuestionDealRecordVo questionDealRecordVo) {
        LinkappUser appUser = linkappUserContextProducer.getNotNullCurrent();
        //参数校验
        cn.hutool.core.lang.Assert.isFalse(questionDealRecordVo.getQuestionId() == null, "问题ID为空");
        cn.hutool.core.lang.Assert.isFalse(questionDealRecordVo.getDealType() == null, "处理类别不能为空");
        cn.hutool.core.lang.Assert.isFalse(StringUtils.isBlank(questionDealRecordVo.getDealMemo()), "说明不能为空");
        // cn.hutool.core.lang.Assert.isFalse(StringUtils.isBlank(questionDealRecordVo.getDealImgs()), "处理图片不能为空");
        //处理类型
        Integer dealType = questionDealRecordVo.getDealType();
        Integer passType = questionDealRecordVo.getPassType();
        if (dealType.intValue() == 2) {
            cn.hutool.core.lang.Assert.isFalse(passType == null, "通过状态不能为空");
        }

        //避免冲突要加锁吗？

        //查询问题
        Long questionId = questionDealRecordVo.getQuestionId();
        QualityQuestionInfo questionInfo = questionInfoMapper.getOneById(questionId);
        cn.hutool.core.lang.Assert.isFalse(questionInfo == null, "问题数据不存在");

        //查询处理记录
        List<QualityQuestionDealRecord> dealRecordList = this.baseMapper.selectDealListByQuestionId(questionId);
        Integer step = 1;
        if (CollectionUtils.isNotEmpty(dealRecordList)) {
            step = dealRecordList.stream().mapToInt(QualityQuestionDealRecord::getStep).max().orElse(1) + 1;
        }
        QualityQuestionDealRecord dealRecord = new QualityQuestionDealRecord();
        BeanUtil.copyProperties(questionDealRecordVo, dealRecord, CopyOptions.create().setIgnoreNullValue(true));
        dealRecord.setCreator(String.valueOf(appUser.getId()));
        dealRecord.setStep(step);
        dealRecord.setDeleteState(1);
        dealRecord.setDealTime(DateUtil.date());
        dealRecord.setCreateTime(dealRecord.getDealTime());
        dealRecord.setBeforeState(questionInfo.getQuestionState());
        if (dealType.intValue() == 1) {
            //整改, -> 待复核
            dealRecord.setAfterStste(2);
        }
        if (dealType.intValue() == 2) {
            //复核，判断通过状态
            if (passType.intValue() == 0) {
                //不通过，不合格
                dealRecord.setAfterStste(4);
            }
            if (passType.intValue() == 1) {
                //通过 -> 合格
                dealRecord.setAfterStste(3);
            }
        }
        this.baseMapper.insert(dealRecord);
        //更新问题状态
        questionInfo.setModifier(dealRecord.getCreator());
        questionInfo.setModifyTime(DateUtil.date());
        questionInfo.setQuestionState(dealRecord.getAfterStste());
        questionInfoMapper.updateById(questionInfo);


        //发送消息
        if (Integer.valueOf(1).equals(dealType)){
            //整改
            QualityMessageUtils.saveDealMessage(questionId,true);
        }else {
            //复查
            QualityMessageUtils.saveReviewMessage(Integer.valueOf(1).equals(passType),questionId,true);
        }

        return RestBuilders.successBuilder().build();
    }

    @Override
    public QualityQuestionDealRecord getOneById(Serializable id) {
        return baseMapper.getOneById(id);
    }

    /**
     * 校验重复
     */
    private void validRepeat(QualityQuestionDealRecord appQualityQuestionDealRecord) {
        /* QueryWrapper<QualityQuestionDealRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", appQualityQuestionDealRecord.getName());
        queryWrapper.eq("tenant_id", linkappUserContextProducer.getNotNullCurrent().getTenantId());
        List<QualityQuestionDealRecord> list = baseMapper.selectList(queryWrapper);
        if (list.size() == 0) {
            return;
        }
        if (list.size() > 1) {
            throw new BusinessException("名称有重复");
        }
        if (ObjectUtils.isEmpty(appQualityQuestionDealRecord.getId())) {
            throw new BusinessException("名称已存在");
        }
        if (!appQualityQuestionDealRecord.getId().equals(list.get(0).getId())) {
            throw new BusinessException("名称已存在");
        }
                    */

    }


    /**
     * 校验参数必填
     */
    private void validParamRequired(QualityQuestionDealRecord appQualityQuestionDealRecord) {
        //Assert.notNull(appQualityQuestionDealRecord, "参数为空");
        //Assert.isTrue(StringUtils.isNotBlank(appQualityQuestionDealRecord.getName()), "名称为空");
    }

    /**
     * 校验参数格式
     */
    private void validParamFormat(QualityQuestionDealRecord appQualityQuestionDealRecord) {
        //Assert.isTrue(appQualityQuestionDealRecord.getName() == null || appQualityQuestionDealRecord.getName().length() <= 50,
        //        "名称超长");
    }
}

